<template>
  <div class="app-container">
    <LeftSide
        :categories="categories"
        :active-category="activeCategory"
        @category-select="handleCategorySelect"
    />
    <AppList
        :myapps="appslist"
        :current-category="activeCategory"
        @install="handleInstall"
    />
  </div>
</template>

<script setup lang="ts">
import {ref} from 'vue';
import LeftSide from './ClassifyLeftSide.vue';
import AppList from './ClassifyAppList.vue';
import axios from 'axios';

// 创建axios实例
const service = axios.create({
  // baseURL: '/appstore', // 注意这里是 /appstore，不要写完整的 http://localhost:8080/appstore
  timeout: 5000
});

// 请求拦截器
service.interceptors.request.use(
    config => {
      // 可以在这里添加认证头
      return config;
    },
    error => {
      console.error('请求错误:', error);
      return Promise.reject(error);
    }
);

// 响应拦截器
// service.interceptors.response.use(
//     response => {
//       return response.data;
//     },
//     error => {
//       console.error('响应错误:', error);
//       return Promise.reject(error);
//     }
// );

const categories = ref([
  '教育',
  '游戏',
  '出行导航',
]);

const categoryToAppType: Record<string, number> = {
  '教育': 1,
  '游戏': 2,
  '出行导航': 3,
};

//默认设置为游戏
const activeCategory = ref('游戏');
const appslist = ref([]);

const fetchApps = async (category: string) => {
  const appType = categoryToAppType[category];
  console.log('正在获取应用数据:', { category, appType });
  try {
     service.get('/api/appstore/apps', { params: { appType } })
        .then(response => {
          console.log('API响应数据:', response.data);
          appslist.value = response.data;
        })
        .catch(error => {
          console.log('更新后的应用列表:', appslist.value);
        });
  } catch (error) {
    console.error('获取应用数据失败', error);
    // console.error('错误详情:', error.response?.data || error.message);
    appslist.value = [];
  }
};

const handleCategorySelect = (key: string) => {
  activeCategory.value = key;
  fetchApps(key);
};

// 初始化时加载默认类别
fetchApps(activeCategory.value);

// 测试后端连接
const testBackendConnection = async () => {
  try {
    console.log('测试后端连接...');
    const response = await service.get('/apps', { params: { appType: 2 } });
    console.log('后端连接成功，测试数据:', response);
  } catch (error) {
    console.error('后端连接失败:', error);
    console.error('请检查后端服务是否在 http://localhost:8080 运行');
  }
};

// 组件挂载时测试连接
testBackendConnection();

const handleInstall = (app: any) => {
  console.log(`安装 ${app.name}`);
};
</script>

<style scoped>
.app-container {
  display: flex;
  min-height: 100vh;
}
</style>
